<?php

namespace App\Admin\Controllers\OwnerItem;

// 账单列表
use App\Admin\Actions\Grid\Document;
use App\Admin\Actions\Grid\Paid;
use App\Models\HouseFeeConfig;
use App\Models\Owner;
use App\Models\OwnerItem;
use App\Services\SendService;
use Barryvdh\Snappy\Facades\SnappyPdf;
use Dcat\Admin\Grid;
use Dcat\Admin\IFrameGrid;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Widgets\Alert;
use PDF;

class PendingBillController extends CommonOwnerItemController
{
    public function index(Content $content)
    {
        if (request(IFrameGrid::QUERY_NAME)) {
            return $content->perfectScrollbar()->body($this->iFrameGrid());
        }

        $info = '<i class="fa fa-exclamation-circle"></i> 由于这是测试版，目前房租催收信息发送为抄表后立即发送，管理员信息发送为15天一次<br>&nbsp;&nbsp;&nbsp;&nbsp;如果未填写杂费（比如：水费，电费），系统不会发送缴费通知给租客';
        return $content
            ->title($this->title())
            ->description($this->description()['index'] ?? trans('admin.list'))
            ->body(Alert::make($info)->info())
            ->body($this->grid());
    }

    protected $title = "未收账单";

    protected function customGrid(Grid $grid)
    {
        $grid->other_amount('杂费')->if(function ($column) {
            return $column->getValue();
        })->then(function (Grid\Column $column) {
            return $column->getValue();
        })->else(function (Grid\Column $column) {
            return $column->modal('杂费列表', function () {
                $owner = Owner::query()->find($this->owner_id);
                if ($owner->config) {
                    $input = "";
                    foreach ($owner->config as $item) {
                        $config = HouseFeeConfig::query()->find($item['house_config_id']);
                        $input .= <<< HTML
        <div class="input-group mb-3">
          <div class="input-group-prepend">
            <span class="input-group-text">请输入本期{$config->name}费（{$item['price']}元/{$config['unit']}）</span>
          </div>
          <input type="text" name="{$config->name}" class="form-control" aria-label="Amount (to the nearest dollar)">
          <div class="input-group-append">
            <span class="input-group-text">￥</span>
          </div>
        </div>
HTML;
                    }

                    $url = route('admin.meter-reading.update-other-amount', ['bill' => $this->id]);
                    $_token = csrf_token();

                    return <<< HTML
<div style='padding:10px 10px 0'>
    <div class="alert alert-primary" role="alert">请注意：当前为测试版，还没有抄表功能，所以这里直接填写本周期各项杂项的价格</div>
    <div>
        <form action="{$url}" method="post">
        <input type="hidden" name="_token" value="{$_token}">
        {$input}
        <button type="submit" class="btn btn-primary">提交</button>
        </form>
    </div>
</div>
HTML;
                }
            });
        });

        // 增加确认支付按钮
        $grid->actions(new Paid());

        $grid->actions(function (Grid\Displayers\Actions $actions) {
            // append一个操作
            $url = route('admin.pending-bill.pdf', ['bill' => $actions->row->id]);
            $actions->append('<a target="_blank" href="'.$url.'">下载单据</a>');
        });
    }

    // 更新总金额， 其他金额同时发送短信
    public function updateOtherAmount(OwnerItem $bill, SendService $sendService)
    {
        $bill->load('owner.user');
        $data = request()->all();
        unset($data['_token']);
        $bill->other_amount = $data;
        $other_price = 0;
        foreach (array_values($data) as $value) {
            $other_price += doubleval($value);
        }
        $bill->total_amount = doubleval($bill->rent) + $other_price;
        $bill->save();
        // 同时发送短信通知用户
        $sendService->qcloud($bill->owner->user->mobile, $bill->total_amount . "元");
        return \response()->redirectTo(route('admin.pending-bill.index'));
    }

    private function getBill($bill)
    {
        $bill = OwnerItem::query()->with('owner.user')->find($bill);
        foreach ($bill->owner->config as $key => $value) {
            $arr[$key] = array_merge($bill->owner->config[$key], HouseFeeConfig::query()->find($value['house_config_id'])->toArray());
            $arr[$key]['amount'] = array_values($bill->other_amount)[$key];
        }
        $bill->owner->config = $arr;
        return $bill;
    }

    // 显示单据
    public function document($bill, Content $content)
    {
        $bill = $this->getBill($bill);
        return $content->full()->body(view('admin.pending_bill.document', compact('bill')));
    }

    // 显示单据pdf
    public function documentPdf($bill)
    {
        if (!OwnerItem::query()->find($bill)->total_amount) {
            admin_warning('请先填写杂费或者抄表');
            return \response()->redirectTo(route('admin.running-water.index'));
        }
        $bill = $this->getBill($bill);
        $pdf = SnappyPdf::loadView('admin.pending_bill.document', compact('bill'));
        $pdf->setOption('encoding', 'utf-8');
        return $pdf->inline('单据.pdf');
    }

    protected function customDetail($show)
    {
    }

    protected function map(): array
    {
        return [
            ['pay_at', '=', null]
        ];
    }
}
